<?php

namespace App\Service\Activity;

use App\Model\Act\InviteRewardLog;
use App\Model\UserProfile;
use App\Service\BaseService;
use Hyperf\DbConnection\Db;

/**
 * 邀请有奖页面-我的奖励
 */
class MyRewardService extends BaseService
{
    public function handle()
    {
        // $userId = $this->getUserId();
        $inviteProfileId = $this->request->input('invite_code', '');
        $userProfile = UserProfile::getInfoByProfileId($inviteProfileId);
        $ret = ['list' => [], 'total_coin' => 0, 'total' => 0];
        if (!$userProfile) return $ret;

        //用户ID
        $userId = $userProfile->user_id;
        return $this->getNewList($inviteProfileId, $userId);
    }

    function getNewList($profileId = '', $userId)
    {
        $where = ['user_id' => $userId, 'flag' => 1];
        $result = InviteRewardLog::where($where)->select(Db::raw('SUM(reward_coin) as total_coin'))->first();
        $ret['total_coin'] = $result && $result->total_coin ? round($result->total_coin, 1) : 0;
        $ret['total'] = UserProfile::getInviteCount($profileId);
        $ret['list'] = [];
        $profiles = UserProfile::where('invite_code', $profileId)->orderBy('user_id', 'desc')->get()->toArray();
        foreach ($profiles as $profile) {
            array_push($ret['list'], [
                'user_id' => !empty($profile['user_profile_id']) ?  $profile['user_profile_id'] : '',
                'time' => date('Y-m-d', strtotime($profile['created_at'])),
                'nick_name' => $profile['nick_name'],
                'avatar' => UserProfile::buildAvatar($profile['avatar']),
            ]);
        }
        return $ret;
    }
}
